package com.ruoyi.userinfo.contorller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户信息Controller
 *
 * @author ruoyi
 * @date 2025-01-10
 */

@RestController
@RequestMapping("/user")
public class UserInfoController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;
    /**
     * 修改个人信息
     */
    @PutMapping("/updateUserInfo")
    public AjaxResult updatePersonalInfo(@RequestBody SysUser user) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();

        currentUser.setNickName(user.getNickName());
        currentUser.setUserName(user.getUserName());
        currentUser.setSex(user.getSex());

        // 校验数据唯一性 账号和昵称
        if (StringUtils.isNotEmpty(user.getUserName()) && !sysUserService.checkUserNameUnique(currentUser)) {
            return error("修改失败，账号已存在");
        } else if (StringUtils.isNotEmpty(user.getNickName()) && !sysUserService.checkNickNameUnique(currentUser)) {
            return error("修改失败，昵称已存在");
        }
        if (sysUserService.updateUserProfile(currentUser) > 0)
        {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }
}